<template>
    <div class="white-box">
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">订单流水：</span>
                <el-input
                    placeholder="请输入订单流水号"
                    v-model="state.orderCode"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">下单方式：</span>
                <el-select
                    v-model="state.createType"
                    placeholder="请选择下单方式"
                    clearable
                >
                    <el-option
                        v-for="item in state.placeOrderTypeList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">订单状态：</span>
                <el-select
                    v-model="state.orderStatus"
                    placeholder="请选择订单状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.orderStatusList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">订单归属：</span>
                <el-select
                    v-model="state.ownerType"
                    placeholder="请选择订单归属类型"
                    clearable
                >
                    <el-option
                        v-for="item in state.orderOwnerTypeList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">支付状态：</span>
                <el-select
                    v-model="state.payStatus"
                    placeholder="请选择支付状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.payStatusList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">所属线路：</span>
                <SelectLoadMore
                    v-model:selectValue="state.lineSid"
                    v-model:options="state.lineOptions"
                    value="sid"
                    label="lineName"
                    popperClass="line"
                    placeholder="请选择线路"
                    :apiFun="getLineOptions"
                />
            </div>
            <div class="task-one__item">
                <span class="task-one__label">取货人员：</span>
                <SelectLoadMore
                    v-model:selectValue="state.realPickerSid"
                    v-model:options="state.pickerOptions"
                    value="sid"
                    label="nickName"
                    popperClass="picker"
                    placeholder="请选择取货员"
                    :apiFun="getPickerOptions"
                />
            </div>
            <div class="task-one__item">
                <span class="task-one__label">寄件姓名：</span>
                <el-input
                    placeholder="请输入寄件人名称"
                    v-model="state.senderName"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">寄件电话：</span>
                <el-input
                    placeholder="请输入寄件人电话"
                    v-model="state.senderPhone"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">收件姓名：</span>
                <el-input
                    placeholder="请输入收件人名称"
                    v-model="state.receiveName"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">收件电话：</span>
                <el-input
                    placeholder="请输入收件人电话"
                    v-model="state.receivePhone"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__btn clearfix">
                <el-button
                    type="primary"
                    :loading="loading"
                    icon="Search"
                    @click="handleSearch"
                    >搜索</el-button
                >
            </div>
        </div>

        <div>
            <el-button
                class="table-mb"
                v-hasPermi="['enttp:order:del']"
                @click="onClickDel()"
                >批量删除订单</el-button
            >
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @selection-change="selectionChange"
            @sort-change="sortChange"
        >
            <el-table-column
                type="selection"
                width="55"
                v-hasPermi="['enttp:order:del']"
            />
            <el-table-column
                prop="orderCode"
                label="订单流水号"
                min-width="200"
                fixed="left"
            ></el-table-column>
            <el-table-column
                label="已分配运单"
                min-width="200"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            >
                <template #default="{ row }">
                    {{
                        row.waybillResultDTOS
                            .map((item) => item.wayBillCode)
                            .join("，")
                    }}
                </template>
            </el-table-column>
            <el-table-column prop="ownerType" label="订单归属" min-width="120">
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName(
                            "order_owner_type",
                            row.ownerType
                        )
                    }}
                </template>
            </el-table-column>
            <el-table-column prop="createType" label="下单方式" min-width="120">
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName(
                            "order_create_type",
                            row.createType
                        )
                    }}
                </template>
            </el-table-column>
            <el-table-column
                prop="ownerName"
                label="下单用户"
                min-width="120"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            />
            <el-table-column
                prop="orderStatus"
                label="订单状态"
                min-width="140"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            >
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName(
                            "order_status",
                            row.orderStatus
                        )
                    }}
                </template>
            </el-table-column>
            <el-table-column prop="realAmount" label="实际金额" min-width="120">
                <template #default="{ row }">
                    {{ fenToYuan(row.realAmount) }}元
                </template>
            </el-table-column>
            <el-table-column prop="payStatus" label="支付状态" min-width="160">
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName("pay_status", row.payStatus)
                    }}
                </template>
            </el-table-column>
            <el-table-column prop="vehicle" label="运输方式" min-width="120" />
            <el-table-column prop="preserve" label="保藏方式" min-width="120">
            </el-table-column>

            <el-table-column
                prop="deliveryType"
                label="提货类型"
                min-width="120"
            >
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName(
                            "line_delivery_type",
                            row.deliveryType
                        )
                    }}
                </template>
            </el-table-column>
            <el-table-column
                prop="line"
                label="线路"
                min-width="200"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            >
                <template #default="{ row }">
                    {{ row.lineStart.fullName }} - {{ row.lineEnd.fullName }}
                </template>
            </el-table-column>
            <el-table-column
                prop="created"
                label="创建时间"
                min-width="160"
                sortable="custom"
                fixed="right"
            />
            <el-table-column
                label="操作"
                width="200"
                class-name="operation-nav"
                fixed="right"
            >
                <template #default="{ row }"
                    ><MoreBtn
                        :buttons="[
                            {
                                props: {
                                    onClick: () => onClickDetails(row.sid),
                                    'v-hasPermi': ['enttp:order:bySidInfo'],
                                },
                                text: '详情',
                            },
                            {
                                props: {
                                    onClick: () => onClickEdit(row.sid),
                                    'v-hasPermi': ['enttp:order:update'],
                                },
                                text: '修改',
                            },
                            {
                                props: {
                                    onClick: () => onClickCreate(row.sid),
                                    'v-hasPermi': ['enttp:waybill:allWaybill'],
                                },
                                text: '分配运单',
                                isRender: [3, 4].includes(row.orderStatus),
                            },
                            {
                                props: {
                                    onClick: () => onClickCompensate(row.sid),
                                    'v-hasPermi': ['enttp:order:adjust:create'],
                                },
                                text: '补款',
                                isRender: row.payStatus === 2,
                            },
                            {
                                props: {
                                    onClick: () => onClickExamine(row.sid),
                                    'v-hasPermi': ['enttp:order:examine'],
                                },
                                text: '审核',
                                isRender: row.payStatus === 4,
                            },
                            {
                                props: {
                                    onClick: () => onClickAdjustRecord(row.sid),
                                    'v-hasPermi': ['enttp:order:adjust:query'],
                                },
                                text: '调整记录',
                            },
                            {
                                props: {
                                    onClick: () => onClickChangePicker(row.sid),
                                    'v-hasPermi': ['enttp:order:editPicker'],
                                },
                                text: '修改取货员',
                                isRender: row.orderStatus < 3,
                            },
                            {
                                props: {
                                    onClick: () => onClickDel(row.sid),
                                    'v-hasPermi': ['enttp:order:del'],
                                },
                                text: '删除',
                            },
                        ]"
                    />
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="slot, sizes, prev, pager, next, jumper"
        >
            <span class="color-#606266"
                >共&nbsp;{{
                    totalNums >= 100 * pageSize
                        ? `${100 * pageSize}+`
                        : totalNums
                }}&nbsp;条</span
            >
        </el-pagination>
    </div>

    <el-drawer v-model="state.showDetail" title="订单详情" size="540">
        <template v-if="detail">
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">订单流水号</el-col>
                <el-col :span="18">{{ detail.orderCode }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">已分配运单</el-col>
                <el-col :span="18">
                    <p v-for="item in detail.waybillResultDTOS" :key="item.sid">
                        {{ item.wayBillCode }}
                        【{{
                            dictStore.getDictMemberName(
                                "waybill_state",
                                item.wayBillState
                            )
                        }}】
                    </p>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">订单归属</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName(
                        "order_owner_type",
                        detail.ownerType
                    )
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">下单方式</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName(
                        "order_create_type",
                        detail.createType
                    )
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">下单用户</el-col>
                <el-col :span="18">{{ detail.ownerName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">订单状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName(
                        "order_status",
                        detail.orderStatus
                    )
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">运输方式</el-col>
                <el-col :span="18">{{ detail.vehicle }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">保藏方式</el-col>
                <el-col :span="18">{{ detail.preserve }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">线路</el-col>
                <el-col :span="18"
                    >{{ detail.lineStart.fullName }} -
                    {{ detail.lineEnd.fullName }}</el-col
                >
            </el-row>
            <!-- 退款进度 -->
            <template v-if="detail.payStatus === 5 && detail.refundProgress">
                <el-divider content-position="left" border-style="dashed"
                    ><el-text type="info" size="small"
                        >退款进度</el-text
                    ></el-divider
                >
                <el-row :gutter="20" class="mb-20">
                    <el-col :span="6" align="end">退款金额</el-col>
                    <el-col :span="18"
                        >{{
                            fenToYuan(detail.refundProgress.refundAmount)
                        }}元</el-col
                    >
                </el-row>
                <el-row :gutter="20" class="mb-20">
                    <el-col :span="6" align="end">退款时间</el-col>
                    <el-col :span="18">{{
                        detail.refundProgress.refundTime
                    }}</el-col>
                </el-row>
                <el-row :gutter="20" class="mb-20">
                    <el-col :span="6" align="end">退款状态</el-col>
                    <el-col :span="18">{{
                        dictStore.getDictMemberName(
                            "order_refund_status",
                            detail.refundProgress.refundStatus
                        )
                    }}</el-col>
                </el-row>
                <el-row
                    v-if="detail.refundProgress.refundStatus === 1"
                    :gutter="20"
                    class="mb-20"
                >
                    <el-col :span="6" align="end">到账时间</el-col>
                    <el-col :span="18">{{
                        detail.refundProgress.arrivedTime
                    }}</el-col>
                </el-row>
            </template>

            <!-- 支付信息 -->
            <el-divider content-position="left" border-style="dashed"
                ><el-text type="info" size="small"
                    >支付信息</el-text
                ></el-divider
            >
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">支付状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName("pay_status", detail.payStatus)
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">原始金额</el-col>
                <el-col :span="18"
                    >{{ fenToYuan(detail.originalAmount) }}元</el-col
                >
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">优惠金额</el-col>
                <el-col :span="18"
                    >{{ fenToYuan(detail.couponAmount) }}元</el-col
                >
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">实际金额</el-col>
                <el-col :span="18">{{ fenToYuan(detail.realAmount) }}元</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">已支付金额</el-col>
                <el-col :span="18"
                    >{{ fenToYuan(detail.alreadyAmount) }}元</el-col
                >
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">待支付金额</el-col>
                <el-col :span="18"
                    >{{ fenToYuan(detail.pendingAmount) }}元</el-col
                >
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">支付时间</el-col>
                <el-col :span="18">{{ detail.payTime }}</el-col>
            </el-row>
            <!-- 货物信息 -->
            <el-divider content-position="left" border-style="dashed"
                ><el-text type="info" size="small"
                    >货物信息</el-text
                ></el-divider
            >
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">货物名称</el-col>
                <el-col :span="18">{{ detail.orderGoods?.goodsName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">货物类型</el-col>
                <el-col :span="18">{{
                    detail.orderGoods?.goodsTypeName
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">计价方式</el-col>
                <el-col :span="18">{{
                    detail.orderGoods?.pricingTypeName
                }}</el-col>
            </el-row>
            <!-- 按重量 -->
            <el-row
                v-if="detail.orderGoods?.pricingType === 1"
                :gutter="20"
                class="mb-20"
            >
                <el-col :span="6" align="end">货物重量</el-col>
                <el-col :span="18"
                    >{{ detail.orderGoods?.goodsWeight }}kg</el-col
                >
            </el-row>
            <!-- 按体积 -->
            <template v-if="detail.orderGoods?.pricingType === 2">
                <el-row :gutter="20" class="mb-20">
                    <el-col :span="6" align="end">货物规格</el-col>
                    <el-col :span="18">{{
                        detail.orderGoods?.goodsNorms
                    }}</el-col>
                </el-row>
                <el-row :gutter="20" class="mb-20">
                    <el-col :span="6" align="end">规格数量</el-col>
                    <el-col :span="18">{{
                        detail.orderGoods?.normsNumber
                    }}</el-col>
                </el-row>
            </template>
            <!-- 取货信息 -->
            <el-divider content-position="left" border-style="dashed"
                ><el-text type="info" size="small"
                    >取货信息</el-text
                ></el-divider
            >
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">取货员</el-col>
                <el-col :span="18">{{ detail.realPickerName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">取货时间</el-col>
                <el-col :span="18">{{ detail.pickerTime || "暂无" }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">上门取件码</el-col>
                <el-col :span="18">{{ detail.pickupCode }}</el-col>
            </el-row>
            <!-- 提货信息 -->
            <!-- <el-divider content-position="left" border-style="dashed"
                ><el-text type="info" size="small"
                    >提货信息</el-text
                ></el-divider
            >
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">提货类型</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName(
                        "line_delivery_type",
                        detail.deliveryType
                    )
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">提货企业</el-col>
                <el-col :span="18">{{ detail.deliveryCompanyName }}</el-col>
            </el-row> -->
            <!-- <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">实际提货员</el-col>
                <el-col :span="18">{{ detail.realDeliveryName }}</el-col>
            </el-row> -->
            <!-- <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">提货时间</el-col>
                <el-col :span="18">{{ detail.deliveryTime }}</el-col>
            </el-row> -->
            <!-- 寄件信息 -->
            <el-divider content-position="left" border-style="dashed"
                ><el-text type="info" size="small"
                    >寄件信息</el-text
                ></el-divider
            >
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">寄件人姓名</el-col>
                <el-col :span="18">{{ detail.senderName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">寄件人电话</el-col>
                <el-col :span="18">{{ detail.senderPhone }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">寄件人地址</el-col>
                <el-col :span="18">{{ detail.senderAddress }}</el-col>
            </el-row>
            <!-- 收件信息 -->
            <el-divider content-position="left" border-style="dashed"
                ><el-text type="info" size="small"
                    >收件信息</el-text
                ></el-divider
            >
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">收件人姓名</el-col>
                <el-col :span="18">{{ detail.receiveName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">收件人电话</el-col>
                <el-col :span="18">{{ detail.receivePhone }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">收件人地址</el-col>
                <el-col :span="18">{{ detail.receiveAddress }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">预计上门时间</el-col>
                <el-col :span="18">{{ detail.reservationTimeRange }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">备注</el-col>
                <el-col :span="18">{{ detail.note }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6" align="end" class="mb-20">状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName("data_status", detail.status)
                }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6" align="end" class="mb-20">创建时间</el-col>
                <el-col :span="18">{{ detail.created }}</el-col>
            </el-row>
        </template>
        <el-backtop target=".el-drawer__body" :bottom="100" />
    </el-drawer>

    <el-dialog v-model="state.showWaybills" title="分配运单" width="1000">
        <el-table
            v-loading="state.wayBillsLoading"
            :data="state.waybills"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            max-height="500px"
            border
            element-loading-background="rgba(255, 255, 255, 0.6)"
        >
            <el-table-column
                prop="wayBillCode"
                label="运单流水号"
                min-width="150"
                fixed="left"
            >
            </el-table-column>
            <el-table-column
                prop="wayBillState"
                label="运单状态"
                min-width="120"
            >
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName(
                            "waybill_state",
                            row.wayBillState
                        )
                    }}
                </template>
            </el-table-column>
            <el-table-column
                prop="created"
                label="创建时间"
                min-width="160"
            ></el-table-column>
            <el-table-column
                label="操作"
                width="150"
                class-name="operation-nav"
                fixed="right"
            >
                <template #default="{ row }"
                    ><MoreBtn
                        :buttons="[
                            {
                                props: {
                                    onClick: () =>
                                        onClickPrintLabel(row.wayBillCode),
                                    'v-hasPermi': ['enttp:labelDesign:list'],
                                },
                                text: '打印',
                            },
                            {
                                props: {
                                    onClick: () => delWaybill(row.sid),
                                    'v-hasPermi': ['enttp:waybill:delete'],
                                },
                                text: '删除',
                                isRender: row.wayBillState === 1,
                            },
                        ]"
                    />
                </template>
            </el-table-column>
        </el-table>
        <el-button
            v-hasPermi="['enttp:waybill:splitWaybill']"
            type="primary"
            plain
            class="mt-10"
            icon="Plus"
            :loading="state.addLoading"
            @click="addWaybill"
            >添加运单</el-button
        >
    </el-dialog>

    <el-dialog v-model="state.showCompensate" title="订单补款" width="350">
        <CompensateOrder
            :sid="state.selectedSid"
            @success="successCompensate"
        />
    </el-dialog>

    <el-dialog v-model="state.showExamine" title="退款审核" width="350">
        <ExamineOrderRefund
            :sid="state.selectedSid"
            @success="successExamine"
        />
    </el-dialog>

    <el-dialog v-model="state.showChangePicker" title="修改取货员" width="350">
        <ChangePicker :sid="state.selectedSid" @success="successChangePicker" />
    </el-dialog>

    <el-dialog v-model="state.showPrint" title="打印面单" width="800">
        <template v-if="state.showCode">
            <svg id="wayBillCode"></svg>
            <svg id="orderCode"></svg>
        </template>

        <div
            id="labelTemplate"
            ref="renderContentRef"
            class="flex justify-center"
        ></div>
        <div v-if="state.labelTemplate" class="mt-20 text-end">
            <el-button type="primary" plain @click="print">确认打印</el-button>
        </div>
    </el-dialog>

    <el-dialog
        v-model="state.showAdjustRecord"
        title="订单调整记录"
        width="1200"
    >
        <OrderAdjustRecord
            :sid="state.selectedSid"
            :show="state.showAdjustRecord"
        />
    </el-dialog>
</template>

<script setup>
import {
    inject,
    reactive,
    onMounted,
    onActivated,
    toRefs,
    ref,
    nextTick,
    onBeforeUnmount,
} from "vue";
import { useRouter } from "vue-router";
import OneLoad from "@mixins/one-load";
import MoreBtn from "@/components/MoreBtn.vue";
import { ElMessageBox } from "element-plus";
import {
    getOrders,
    getOrderDetail,
    delOrders,
    getOrderRefundProgress,
} from "@/apis/order/order";
import {
    distributionWaybills,
    getOrderWaybills as getOrderWaybillsApi,
    delOrderWaybill,
} from "@/apis/order/waybill";
import { getLines } from "@/apis/enterprise/line.js";
import { getPickers } from "@/apis/user/user.js";
import {
    getLabelTemplates,
    getLabelTemplateContent,
} from "@/apis/enterprise/labelTemplate.js";
import SelectLoadMore from "@/components/selectLoadMore.vue";
import CompensateOrder from "./CompensateOrder.vue";
import OrderAdjustRecord from "./OrderAdjustRecord.vue";
import ExamineOrderRefund from "./ExamineOrderRefund.vue";
import ChangePicker from "./ChangePicker.vue";
import JsBarcode from "jsbarcode";
import renderVnode from "@/mixins/render-vnode.js";
import { fenToYuan } from "@/assets/common/utils.js";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status");
dictStore.getDictMembers("line_delivery_type");
dictStore.getDictMembers("order_refund_status");
dictStore.getDictMembers("waybill_state");
dictStore
    .getDictMembers("order_create_type")
    .then((res) => (state.placeOrderTypeList = res));
dictStore
    .getDictMembers("order_status")
    .then((res) => (state.orderStatusList = res));
dictStore
    .getDictMembers("order_owner_type")
    .then((res) => (state.orderOwnerTypeList = res));
dictStore
    .getDictMembers("pay_status")
    .then((res) => (state.payStatusList = res));

const router = useRouter();
const $message = inject("$message");
// 打印面单dom
const renderContentRef = ref(null);
const state = reactive({
    placeOrderTypeList: [],
    orderStatusList: [],
    orderOwnerTypeList: [],
    payStatusList: [],
    ascended: false,
    sortFieldName: "created",
    createType: null,
    lineSid: null,
    orderCode: null,
    orderStatus: null,
    ownerType: null,
    payStatus: null,
    // realDeliverySid: null,
    realPickerSid: null,
    receiveName: null,
    receivePhone: null,
    senderName: null,
    senderPhone: null,
    showWaybills: false, // 分配运单
    addLoading: false,
    waybillsLoading: false,
    waybills: [],
    detail: null,
    showDetail: false, // 详情
    selectedSid: null,
    lineOptions: [], // 线路列表
    takePickerOptions: [], // 提货员列表
    pickerOptions: [], // 取货员列表
    showPrint: false,
    labelTemplate: "", // 面单模板内容
    showAdjustRecord: false, // 订单调整记录
    showExamine: false, // 订单退款审核
    showCode: true, // 显示条形码元素 用于生成条形码
    showChangePicker: false, // 显示修改取货员
});

const { detail } = toRefs(state);

onActivated(() => {
    pubParams(getList);
});

onBeforeUnmount(() => {
    iframePrint && iframePrint.remove();
});

const getLineOptions = async (params) => {
    const res = await getLines({
        ...params,
        lineName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getPickerOptions = async (params) => {
    const res = await getPickers({
        ...params,
        userName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 显示订单补款弹窗
const onClickCompensate = (sid) => {
    state.showCompensate = true;
    state.selectedSid = sid;
};

const successCompensate = () => {
    state.selectedSid = null;
    state.showCompensate = false;
    pubParams(getList);
};

/**
 * minxin列表加载
 */
const {
    loading,
    arr_data,
    pubRefreshParams,
    pubParams,
    page,
    pageSize,
    getdata,
    pageSizeNum,
    totalNums,
    openPaging,
} = OneLoad();

openPaging(getList);

function getList() {
    getdata(
        getOrders({
            current: page.value,
            size: pageSize.value,
            ascended: state.ascended,
            sortFieldName: state.sortFieldName,
            createType: state.createType,
            lineSid: state.lineSid,
            orderCode: state.orderCode,
            orderStatus: state.orderStatus,
            ownerType: state.ownerType,
            payStatus: state.payStatus,
            // realDeliverySid: state.realDeliverySid,
            realPickerSid: state.realPickerSid,
            receiveName: state.receiveName,
            receivePhone: state.receivePhone,
            senderName: state.senderName,
            senderPhone: state.senderPhone,
        })
    );
}

// 搜索
const handleSearch = () => {
    pubRefreshParams(getList);
};

// 排序
const sortChange = (e) => {
    const { property, order } = e.column;
    state.ascended = order === "ascending";
    state.sortFieldName = order ? property : null;
    pubRefreshParams(getList);
};

const onClickDetails = async (sid) => {
    state.showDetail = true;
    state.detail = null;
    await getDetails(sid);
    // 支付状态 已退款
    if (state.detail.payStatus === 5) {
        // getRefundProgress();
    }
};

const getDetails = async (sid) => {
    const res = await getOrderDetail({ sid });
    if (res.data.code == 200) {
        state.detail = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 查看订单退款进度
const getRefundProgress = async () => {
    const res = await getOrderRefundProgress({ sid: state.detail.sid });
    if (res.data.code == 200) {
        state.detail.refundProgress = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 点击修改按钮
const onClickEdit = (sid) => {
    sid &&
        router.push({
            name: "OrderEdit",
            query: {
                sid,
            },
        });
};

// 选中项改变
const selectionChange = (e) => {
    state.sidList = e.map((item) => item.sid);
};

// 删除
const onClickDel = async (sid) => {
    if (sid) {
        state.sidList = [sid];
    }
    if (!state.sidList.length) {
        return $message({ message: "请先勾选要删除的数据", type: "warning" });
    }
    await ElMessageBox.confirm("确定删除订单吗？");
    const res = await delOrders({ sidList: state.sidList });
    if (res.data.code == 200) {
        $message({ message: "删除成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const onClickCreate = async (sid) => {
    state.showWaybills = true;
    state.waybills = [];
    state.selectedSid = sid;
    await getOrderWaybills();
};

const getOrderWaybills = async () => {
    state.waybillsLoading = true;
    const res = await getOrderWaybillsApi({ sid: state.selectedSid });
    if (res.data.code == 200) {
        state.waybills = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
    state.waybillsLoading = false;
};

const delWaybill = async (sid) => {
    state.waybillsLoading = true;
    const res = await delOrderWaybill({ sidList: [sid] });
    if (res.data.code == 200) {
        getOrderWaybills();
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
    state.waybillsLoading = false;
};

const addWaybill = async () => {
    state.addLoading = true;
    const res = await distributionWaybills({ sid: state.selectedSid });
    if (res.data.code == 200) {
        getOrderWaybills();
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
    state.addLoading = false;
};

const { renderContent } = renderVnode();
// 点击打印面单
const onClickPrintLabel = async (wayBillCode) => {
    const {
        orderCode,
        senderName,
        senderPhone,
        senderAddress,
        receiveName,
        receivePhone,
        receiveAddress,
        lineStart,
        lineEnd,
        deliveryCompanyName,
        pickerTime,
    } = arr_data.value.find((item) => item.sid === state.selectedSid);
    // 面单模板字典
    const dict = {
        wayBillCode,
        orderCode,
        senderName,
        senderPhone,
        senderAddress,
        receiveName,
        receivePhone,
        receiveAddress,
        line: lineStart.fullName + " ——> " + lineEnd.fullName,
        deliveryCompanyName,
        pickerTime,
    };
    state.showPrint = true;
    state.showCode = true;
    const content = await getEnableLabelTemplate();
    state.labelTemplate = content;

    let json;
    try {
        json = JSON.parse(state.labelTemplate);
    } catch (error) {
        $message({ message: "面单模板解析错误", type: "error" });
    }
    state.labelTemplate = JSON.stringify(labelTemplateDictReplace(dict, json));
    nextTick(() => {
        renderContent(state.labelTemplate, renderContentRef.value);
        state.showCode = false;
    });
};

// 将面单模板的预览内容替换为真实数据
const labelTemplateDictReplace = (dict, json) => {
    for (let k in json) {
        if (k === "key") {
            // key属性，记录要渲染数据的字段
            const key = json[k];
            // 生成条形码
            if (["wayBillCode", "orderCode"].includes(key)) {
                JsBarcode(`#${key}`, dict[key], {
                    width: 1.25,
                    height: 50,
                    fontSize: 13,
                });
                const svg = document.getElementById(key);
                svg.style.width = "100%";
                delete json.children;
                if (Object.hasOwn(json, "props")) {
                    json.props.innerHTML = svg.outerHTML;
                } else {
                    json.props = { innerHTML: svg.outerHTML };
                }
            } else {
                json.children = dict[key];
            }
        } else if (k === "children") {
            const children = json[k];
            if (Array.isArray(children)) {
                json[k] = children.reduce((pre, cur) => {
                    pre.push(labelTemplateDictReplace(dict, cur));
                    return pre;
                }, []);
            }
        }
    }
    return json;
};

// 获取启用的面单模板
const getEnableLabelTemplate = async () => {
    const res = await getLabelTemplates({ status: 0 });
    if (res.data.code == 200) {
        const templates = res.data.data.records;
        if (templates.length) {
            const sid = templates[0].sid;
            return await getEnableLabelTemplateContent(sid);
        }
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 获取启用的面单模板内容
const getEnableLabelTemplateContent = async (sid) => {
    const res = await getLabelTemplateContent({ sid });
    if (res.data.code == 200) {
        return res.data.data.content;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

let iframePrint;
const print = () => {
    iframePrint = document.getElementById("iframe-print");
    if (!iframePrint) {
        // 创建iframe
        iframePrint = document.createElement("IFRAME");
        iframePrint.setAttribute("id", "iframe-print");
        iframePrint.setAttribute(
            "style",
            "position:absolute;width:0px;height:0px;left:-500px;top:-500px;"
        );
        // 往iframe中写入面单模板
        document.body.appendChild(iframePrint);
        const doc = iframePrint.contentWindow.document;
        //这里可以自定义样式
        doc.write(
            '<style media="print">@page {size: auto;margin: 0mm;}</style>'
        ); //解决出现页眉页脚和路径的问题
        const el = document.getElementById("labelTemplate").children[0];
        doc.write("<div>" + el.outerHTML + "</div>");
        doc.close();
        iframePrint.contentWindow.focus();
    }
    nextTick(() => {
        iframePrint.contentWindow.print();
    });
};

const onClickAdjustRecord = (sid) => {
    state.selectedSid = sid;
    state.showAdjustRecord = true;
};

const onClickExamine = (sid) => {
    state.selectedSid = sid;
    state.showExamine = true;
};

const successExamine = () => {
    state.selectedSid = null;
    state.showExamine = false;
    pubParams(getList);
};

const onClickChangePicker = (sid) => {
    state.selectedSid = sid;
    state.showChangePicker = true;
};

const successChangePicker = () => {
    state.selectedSid = null;
    state.showChangePicker = false;
    pubParams(getList);
};
</script>

<style lang="less" scoped></style>
